import React, { useState } from "react";
import { Button, Form, Input, Space } from "antd";
import { ModalComponent } from "@/components/iteration";
import FileIconImg from "./fileIcon/FileIconImg";
import { fileRename } from "@/api/file";
import PropTypes from "prop-types";

const FileReNameComponent = ({ title, file, onCallback, ...resProps }) => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [submitDisable, setSubmitDisable] = useState(false);
  const [form] = Form.useForm();

  const onFinish = async () => {
    const fileName = form.getFieldValue("fileName");
    if (file.fileName === fileName) {
      return setIsModalOpen(false);
    }
    const res = await fileRename(file.fullPath, fileName);
    setIsModalOpen(false);
    // 重命名成功后，更新文件名
    onCallback && onCallback({ ...res });
  };

  return (
    <>
      <Button {...resProps} onClick={() => setIsModalOpen(true)}>
        {title}
      </Button>
      <ModalComponent
        title="文件重命名"
        open={isModalOpen}
        footer={null}
        destroyOnClose
        onCancel={() => setIsModalOpen(false)}
      >
        <div style={{ marginBottom: "16px", textAlign: "center" }}>
          <FileIconImg width="100px" heigth="100px" file={file} />
        </div>
        <Form
          style={{ padding: "0px" }}
          form={form}
          name="validateOnly"
          autoComplete="off"
          initialValues={{ fileName: file.fileName }}
          onFinish={onFinish}
          onReset={() => setIsModalOpen(false)}
          onValuesChange={({ fileName }) => setSubmitDisable(!fileName)}
        >
          <Form.Item name="fileName" rules={[{ required: true }]}>
            <Input variant="filled" />
          </Form.Item>
          <Form.Item style={{ textAlign: "right" }}>
            <Space>
              <Button htmlType="reset">取消</Button>
              <Button type="primary" htmlType="submit" disabled={submitDisable}>
                确定
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </ModalComponent>
    </>
  );
};

FileReNameComponent.propTypes = {
  title: PropTypes.string,
  file: PropTypes.object.isRequired,
  onCallback: PropTypes.func,
};

export default FileReNameComponent;
